<template>
  <section class="supervision-form-content">
    <el-form class="supervision-form"
      ref="form"
      label-width="120px"
      :model="form"
      :rules="formRules"
      :disabled="readonly"
      :show-message="!readonly"
      :hide-required-asterisk="true">
      <el-row>
        <el-col :span="8">
          <el-form-item label="选择供应商" prop="supplierName" required>
            <el-input
              v-model="form.supplierName" placeholder="请选择供应商"
              @focus="displaySupplierDialog()"
              :disabled="readonly || isToBeCheck"
              readonly>
              <el-button
                v-if="!readonly && !isToBeCheck"
                slot="append"
                icon="el-icon-search"
                @click="displaySupplierDialog()"
              ></el-button>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8"  v-if="isRegular">
          <el-form-item label="核查区域" prop="checkAreaName">
            <ManagementAreaSelect
              style="width: 100%"
              ref="checkArea"
              v-model="form.checkArea"
              placeholder="请选择核查区域"
              :hiddenKeys="['1']"
              @onSelected="handleCheckAreaSelect"/>
          </el-form-item>
        </el-col>
        <template v-if="isTemp">
          <el-col :span="8">
            <el-form-item label="单据号" prop="purchaseBill">
              <el-input v-model="form.purchaseBill" placeholder="请输入单据号"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="公司名称" prop="companyName" required>
              <BranchSelect
                v-model="form.companyId"
                @onSelected="handleBranchSelect" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开票供应商" prop="invoiceSupplierName">
              <el-input
                v-model="form.invoiceSupplierName" placeholder="请选择开票供应商"
                @focus="displaySupplierDialog(true)"
                readonly>
                <el-button
                  v-if="!readonly"
                  slot="append"
                  icon="el-icon-search"
                  @click="displaySupplierDialog(true)"
                ></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系电话"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商联系人" prop="contactPerson">
              <el-input v-model="form.contactPerson" placeholder="请输入供应商联系人"/>
            </el-form-item>
          </el-col>
        </template>
        <el-col :span="16">
          <el-form-item label="抽查描述" prop="spotCheckDesc" required>
            <el-input v-model="form.spotCheckDesc" placeholder="请输入抽查描述" type="textarea" autosize/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- <pre>{{form}}</pre> -->
    <!-- <pre>{{regularPriceBill}}</pre> -->
    <!-- <pre>{{tempPriceBill}}</pre> -->
    <div class="supervision-detail">
      <template v-if="isRegular">
        <el-row type="flex">
          <el-col :span="6"><span class="label">供应商级别：</span> {{form.supplierLevel}}</el-col>
          <el-col :span="6"><span class="label">联系方式：</span>
          <span class="ellipsis" :title="form.contactPhone">{{form.contactPhone}}</span></el-col>
          <el-col :span="6"><span class="label">管理区域：</span>{{form.manageAreaName}}</el-col>
          <el-col :span="6"><span class="label">问题类型：</span>{{form.questionTypeName}}</el-col>
        </el-row>
        <el-row type="flex">
          <el-col :span="6"><span class="label">具体原因：</span>{{form.specificCausesName}}</el-col>
          <el-col :span="6"><span class="label">差额：</span>{{form.balance}}</el-col>
          <el-col :span="6"><span class="label">问题等级：</span>{{form.questionLevel}}</el-col>
          <el-col :span="6"><span class="label">下调账金额：</span>{{form.adjustmentAmount}}</el-col>
        </el-row>
        <el-row type="flex">
          <el-col :span="6"><span class="label">下调账单号：</span>
          <span class="ellipsis" :title="form.adjustmentNo">{{form.adjustmentNo}}</span></el-col>
          <el-col :span="6"><span class="label">汇款证明：</span>
            <a :href="form.remittanceCertificate" target="_blank" v-if="isUrl(form.remittanceCertificate)">证明下载</a>
            <span v-else>{{form.remittanceCertificate}}</span>
          </el-col>
          <el-col :span="6"><span class="label">是否有调账：</span>{{form.hasAdjustmentName}}</el-col>
          <el-col :span="6"></el-col>
        </el-row>
      </template>
      <template v-if="isTemp">
        <el-row type="flex">
          <el-col :span="6"><span class="label">采购人：</span>{{form.purchasePersonName}}</el-col>
          <el-col :span="6"><span class="label">下调账金额：</span>{{form.adjustmentAmount}}</el-col>
          <el-col :span="6"><span class="label">下调账单号：</span>
          <span class="ellipsis" :title="form.adjustmentNo">{{form.adjustmentNo}}</span></el-col>
          <el-col :span="6"><span class="label">汇款证明：</span>
            <a :href="form.remittanceCertificate" target="_blank" v-if="isUrl(form.remittanceCertificate)">证明下载</a>
            <span v-else>{{form.remittanceCertificate}}</span>
          </el-col>
        </el-row>
        <el-row type="flex">
          <el-col :span="6"><span class="label">是否价格问题：</span>{{form.hasPriceQuestionName}}</el-col>
          <el-col :span="6"><span class="label">是否有调账：</span>{{form.hasAdjustmentName}}</el-col>
          <el-col :span="6"><span class="label">问题错误类型：</span>{{form.questionTypeName}}</el-col>
          <el-col :span="6"></el-col>
        </el-row>
      </template>
    </div>
    <!-- 供货信息列表 -->
    <p class="buttons-bar" v-if="!readonly">
      <el-button :disabled="isRegular && !form.supplierCode" @click="product.visible=true" type="primary">关联商品</el-button>
      <el-button v-if="isTemp" @click="payable.visible=true" type="primary">关联单据</el-button>
    </p>
    <vxe-table
      size="mini"
      resizable
      class="availability-list"
      show-overflow
      border
      ref="table"
      row-id="id"
      :max-height="'400px'"
      :auto-resize="true"
      :edit-config="editConfig"
      :edit-rules="editRules"
      @edit-closed="updateData"
      :data="tableList">
        <vxe-column type="seq" width="50" title="序号"></vxe-column>
        <vxe-column
          v-for="(column,key) in columns"
          :key="key"
          :field="column.field"
          :title="column.title"
          :minWidth="column.minWidth"
          :edit-render="readonly ? null : column.editRender"
        >
          <template #edit="{ row }">
            <vxe-input
              v-model="row[column.field]"
              :type="column.type || 'number'"
              :min="0"
              :max="999999999"
              :maxlength="column.maxlength || 9"
              :placeholder="`请输入${column.title}数值`"
              :controls="false"
              @change="handleInputChange"
              ></vxe-input>
          </template>
        </vxe-column>

        <vxe-column title="操作" width="80" v-if="!readonly">
          <template #default="{ row, _rowIndex }">
            <vxe-button size="mini" type="text" status="primary" content="删除" @click="removeEvent(row, _rowIndex)"></vxe-button>
          </template>
        </vxe-column>
    </vxe-table>
    <div v-if="readonly">
      <el-divider content-position="left">签字意见</el-divider>
      <BasicTable
        :showSelectCol="false"
        :showPagination="false"
        :columns="checkInfo.columns"
        :dataSource="checkInfo.list"
      />
    </div>
    <SelectSupplierDialog
      :title="supplier.title"
      :invoice="supplier.invoice"
      :supplierVisible.sync="supplier.visible"
      @handle-select="handleGetSupplierInfo"
    />
    <SelectProductDialog
      :type="type"
      :supplierId="form.supplierId"
      :supplierCode="form.supplierCode"
      :areaId="form.checkArea"
      :areaCode="form.checkAreaCode"
      :dialogVisible.sync="product.visible"
      @handle-select="handleGetProductInfo"
      multiple />
    <SelectPayableDialog
      :supplierId="form.supplierId"
      :supplierCode="form.supplierCode"
      :dialogVisible.sync="payable.visible"
      @handle-select="handleGetPayableInfo"
    />
  </section>
</template>

<script>
import SelectSupplierDialog from '@/pages/supplier/components/SelectSupplierDialog'
import SelectProductDialog from '@/pages/supplier/components/SelectProductDialog'
import SelectPayableDialog from '@/pages/supplier/components/SelectPayableDialog'
import ManagementAreaSelect from '@/components/supplier/ManagementAreaSelect'
import BranchSelect from '@/components/supplier/BranchSelect'
import ManageArea from '@/mixins/supplier/manageArea';
import BasicTable from '@/components/supplier/BasicTable';
import { priceSupervisionForm } from '@/pages/supplier/constants'
import { filterArrObjItems, toPercent, toFixed, isUrl } from '@/pages/supplier/utils'
import { getMainBusinessContact } from '@/api/supplier/components';
const {
  getTableColumns,
  getInitialFieldsValue,
  // QUESTION_TYPE_MAP_OBJECT,
  // QUESTION_REASON_MAP_OBJECT,
  QUESTION_LEVEL_MAP_OBJECT,
  SUPPLIER_LEVEL_MAP_OBJECT,
} = priceSupervisionForm

export default {
  mixins: [ManageArea],
  name: 'PriceSupervisionForm',
  components: {
    SelectSupplierDialog,
    SelectProductDialog,
    SelectPayableDialog,
    ManagementAreaSelect,
    BranchSelect,
    BasicTable,
  },
  props: {
    // 类型 正常价格核查:regular 临采价格核查:temp
    type: String,
    // 表是否开启禁用
    readonly: { type: Boolean, default: false },
    // 是否为待核查下推
    isToBeCheck: { type: Boolean, default: false },
    // 数据源
    dataSource: { type: Object, default () { return null } },
  },
  data () {
    const { processId = undefined } = this.$route.query
    const { type, readonly } = this
    const columns = getTableColumns(type, readonly)
    const fieldsValue = getInitialFieldsValue(type, readonly)
    return {
      processId,
      inited: false,
      form: Object.assign({}, fieldsValue),
      // 供应商
      supplier: {
        title: '查询开票供应商',
        invoice: false,
        visible: false,
      },
      // 商品
      product: { visible: false },
      // 单据
      payable: { visible: false },
      columns,
      tableList: [],
      isUrl,
      checkInfo: {
        list: [],
        columns: [
          { title: '人员姓名', key: 'name' },
          { title: '签字意见', key: 'opinion' },
          { title: '签字时间', key: 'opinionTime' }
        ]
      }
    }
  },
  computed: {
    regularPriceBill () {
      const { supplierId, supplierCode, supplierName, supplierLevel, hasAdjustment,
        manageArea, manageAreaName, checkArea, checkAreaName, contactPhone, spotCheckDesc,
        belongDepartment, belongDepartmentName, businessContactName, businessContactId } = this.form
      return {
        supplierId,
        supplierCode,
        supplierName,
        supplierLevel,
        hasAdjustment,
        manageArea,
        manageAreaName,
        checkArea,
        checkAreaName,
        contactPhone,
        spotCheckDesc,
        belongDepartment,
        belongDepartmentName,
        businessContactName,
        businessContactId
      }
    },
    tempPriceBill () {
      const { form, regularPriceBill } = this
      const {
        hasPriceQuestion,
        contactPerson,
        spotCheckDesc,
        invoiceSupplierCode,
        invoiceSupplierName,
        companyId,
        companyName,
        organizeType,
        purchaseBill,
        purchasePersonName,
        purchasePersonNo,
        questionType
      } = form
      return {
        hasPriceQuestion,
        contactPerson,
        spotCheckDesc,
        invoiceSupplierCode,
        invoiceSupplierName,
        companyId,
        companyName,
        organizeType,
        purchaseBill,
        questionType,
        purchasePersonName,
        purchasePersonNo,
        ...regularPriceBill
      }
    },
    formData () {
      const { processId, isRegular, isTemp, tableList, regularPriceBill, tempPriceBill } = this
      // 单据类型，21：正常价格核查，22：临采价格核查
      const obj = { documentType: isRegular ? 21 : 22, }
      if (processId) {
        obj.id = processId
      }
      if (isRegular) {
        return Object.assign({
          supervisionNormalPriceBill: { ...regularPriceBill },
          supervisionNormalPriceRecordBillList: [...filterArrObjItems(tableList)],
        }, obj)
      }
      if (isTemp) {
        return Object.assign({
          supervisionTempPriceBill: { ...tempPriceBill },
          supervisionTempPriceRecordBillList: [...filterArrObjItems(tableList)],
        }, obj)
      }
    },
    formRules () {
      return {
        supplierName: [{ required: true, message: '请选择供应商', trigger: ['blur', 'change', 'clear'] }],
        // checkAreaName: [{ required: true, message: '请选择核查区域', trigger: ['blur', 'change', 'clear'] }],
        // purchaseBill: [{ required: true, message: '请输入单据号', trigger: ['blur', 'change', 'clear'] }],
        companyName: [{ required: true, message: '请选择公司名称', trigger: ['blur', 'change', 'clear'] }],
        // invoiceSupplierName: [{ required: true, message: '请选择开票供应商', trigger: ['blur', 'change', 'clear'] }],
        // contactPhone: [{ required: true, message: '请输入联系电话', trigger: ['blur', 'change', 'clear'] }],
        // contactPerson: [{ required: true, message: '请输入供应商联系人', trigger: ['blur', 'change', 'clear'] }],
        spotCheckDesc: [{ required: true, message: '请输入抽查描述', trigger: ['blur', 'change', 'clear'] }],
      }
    },
    editConfig () {
      if (this.readonly) {
        return {}
      }
      return { trigger: 'click', mode: 'cell', }
    },
    editRules () {
      if (this.isRegular) {
        return {
          // checkPrice: [{ required: true, message: '请输入核查价格' }],
        }
      } else {
        return {
          purchaseCount: [{ required: true, message: '请输入订货数量' }],
          purchasePrice: [{ required: true, message: '请输入订货价格' }],
          // checkPrice: [{ required: true, message: '请输入核查价格' }],
          // otherSupplierPrice: [{ required: true, message: '请输入其他供应商价格' }],
        }
      }
    },
    isRegular () {
      return this.type === 'regular'
    },
    isTemp () {
      return this.type === 'temp'
    },
  },
  watch: {
    dataSource: {
      handler (newVal, oldVal) {
        if (!oldVal && newVal) {
          this.initFormData(_.cloneDeep(newVal))
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 回填数据
    initFormData (data) {
      if (!data) {
        return
      }
      const { item, recordList = [], checkOpinionList = [] } = data
      const isNil = val => {
        return typeof val === 'undefined' || (!val && val !== 0)
      }
      if (item) {
        this.form = item
        if (!isNil(item.questionLevel)) {
          this.form.questionLevel = QUESTION_LEVEL_MAP_OBJECT[item.questionLevel] || item.questionLevel
        }
        /* if (!isNil(item.questionType)) {
          this.form.questionTypeName = this.isRegular ? (item.questionType ? '外部问题' : '内部问题') : QUESTION_TYPE_MAP_OBJECT[item.questionType]
        } */
        if (!isNil(item.hasAdjustment)) {
          this.form.hasAdjustmentName = item.hasAdjustment === 1 ? '是' : '否'
        }
        if (!isNil(item.hasPriceQuestion)) {
          this.form.hasPriceQuestionName = item.hasPriceQuestion === 1 ? '是' : '否'
        }
        /* if (!isNil(item.specificCauses)) {
          this.form.specificCauses = QUESTION_REASON_MAP_OBJECT[item.specificCauses] || item.specificCauses
        } */
      }
      this.tableList = recordList
      this.checkInfo.list = checkOpinionList
    },
    // 显示选择供应商弹窗
    displaySupplierDialog (invoice = false) {
      this.supplier.invoice = invoice
      this.supplier.visible = true
      this.supplier.title = invoice ? '选择开票供应商' : '选择供应商'
    },
    // 获取供应商信息
    handleGetSupplierInfo (row) {
      if (row) {
        if (this.supplier.invoice) {
          const {
            invoiceSupplierCode,
            invoiceSupplierName,
          } = row
          this.form.invoiceSupplierCode = invoiceSupplierCode
          this.form.invoiceSupplierName = invoiceSupplierName
        } else {
          const {
            supplierName, // 供应商编码
            supplierCode, // 供应商编码
            supplierId, // 供应商id
            supplierLevel, // 供应商级别
            managementAreaId, // 管理区域
            managementAreaName,
            belongDepartment,
            belongDepartmentName, // 归属中心
            businessContactName, // 业务对接人
            businessContact
          } = row;
          this.form.supplierName = supplierName
          this.form.supplierId = parseInt(supplierId, 10)
          this.form.supplierCode = supplierCode
          this.form.supplierLevel = SUPPLIER_LEVEL_MAP_OBJECT[supplierLevel]
          // 核查区域没有集团总部，如果供应商管理区域是集团总部，核查区域显示北京区域
          this.form.checkArea = managementAreaId === 1 ? '100' : `${managementAreaId}`
          const manageArea = this.manageArea.find(i => i.manageAreaId === this.form.checkArea)
          if (manageArea) {
            this.form.checkAreaCode = manageArea.manageAreaCode
            this.form.checkAreaName = manageArea.manageAreaName
          }
          this.form.manageArea = managementAreaId
          this.form.manageAreaName = managementAreaName
          this.form.belongDepartment = belongDepartment
          this.form.belongDepartmentName = belongDepartmentName
          this.form.businessContactName = businessContactName
          this.form.businessContactId = businessContact

          if (this.isRegular) {
            this.getContactListBySupplierId(supplierId)
          }
        }
      }
    },
    // 查询联系方式
    async getContactListBySupplierId (supplierId) {
      const resp = await getMainBusinessContact({ supplierId })
      if (resp && resp.result && resp.result.length) {
        const { contactPhone, personName } = resp.result[0]
        this.form.contactPhone = contactPhone
        this.form.contactPerson = personName
      } else {
        this.form.contactPhone = ''
        this.form.contactPerson = ''
      }
    },
    // 核查区域
    handleCheckAreaSelect (data) {
      // console.log('handleManagementAreaSelect :>> ', data);
      if (data) {
        const { manageAreaName: checkAreaName, manageAreaCode } = data
        this.form.checkAreaName = checkAreaName
        this.form.checkAreaCode = manageAreaCode
      } else {
        this.form.checkAreaName = ''
        this.form.checkAreaCode = ''
      }
    },
    // 分公司信息
    handleBranchSelect (data) {
      if (data) {
        this.form.companyId = data.organizeCode
        this.form.companyName = data.organizeName
        this.form.organizeType = data.organizeType
      } else {
        this.form.companyId = 0
        this.form.companyName = ''
        this.form.organizeType = 0
      }
    },
    // 获取商品信息
    handleGetProductInfo (data) {
      // console.log('handleGetProductInfo :>> ', data);
      const uuids = this.tableList.map(i => i.productCode)
      let list = data.filter(i => !uuids.includes(i.productCode))
        .map(i => {
          i.columnType = 2 // columnType: 2 商品
          return i
        })
      list = this.tableList.concat(list)
      this.tableList = list
    },
    // 获取单据信息
    handleGetPayableInfo (data) {
      let list = data.map(i => {
        i.columnType = 1 // columnType: 1 单据
        i.purchaseCount = i.quantity // 订货数量
        i.purchasePrice = i.taxUnivalent // 订货价格
        i.totalAmount = i.taxPriceTotals // 金额总计
        i.unit = i.unitName // 单位
        return i
      })
      const payableList = this.tableList.filter(i => i.columnType === 1)
      if (payableList && payableList.length) {
        if (payableList[0].billNum === list[0].billNum) {
          const uuids = payableList.map(i => i.productId)
          const insertItems = list.filter(i => !uuids.includes(i.productId))
          if (insertItems && insertItems.length) {
            this.tableList.splice(payableList.length - 1, 0, ...insertItems)
          }
        } else {
          this.tableList.splice(0, payableList.length, ...list)
          this.updateSupplier(list[0])
        }
      } else {
        this.tableList = list.concat(this.tableList)
        this.updateSupplier(list[0])
      }
    },
    // 更新供应商信息
    updateSupplier (data) {
      // console.log('updateSupplier', data)
      const {
        supplierId,
        supplierCode,
        supplierName,
        billNum, // 单据号
        billSupplierCode, // 开票供应商
        billSupplierName, // 开票供应商
        supplierPerson, // 供应商联系人
        supplierPersonPhone, // 联系电话
        salesmanName, // 采购人
        salesmanCode, // 采购人code
        spotCheckDesc, // 抽查描述
      } = data
      if (this.form.supplierId !== supplierId) {
        Object.assign(this.form, {
          supplierId,
          supplierCode,
          supplierName,
          spotCheckDesc,
          purchaseBill: billNum,
          invoiceSupplierCode: billSupplierCode,
          invoiceSupplierName: billSupplierName,
          contactPhone: supplierPersonPhone,
          contactPerson: supplierPerson,
          purchasePersonName: salesmanName,
          purchasePersonNo: salesmanCode,
        })
      }
    },
    // 单元格编辑状态下被关闭时会触发该事件
    updateData ({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) {
      // console.log('updateData', { row, rowIndex, $rowIndex, column, columnIndex, $columnIndex })
      const { field } = column
      const { price, checkPrice, purchaseCount, purchasePrice, otherSupplierPrice } = row
      const isPriceValid = price && !isNaN(price)
      const isCheckPriceValid = checkPrice && !isNaN(checkPrice)
      const isPurchaseCountValid = purchaseCount && !isNaN(purchaseCount)
      const isPurchasePriceValid = purchasePrice && !isNaN(purchasePrice)
      const isOtherSupplierPriceValid = otherSupplierPrice && !isNaN(otherSupplierPrice)
      const { isRegular } = this
      if (isRegular) {
        // 正常价格核查
        if (isPriceValid && isCheckPriceValid) {
          row.priceRatio = toPercent(checkPrice / price - 1, 3)
        } else {
          row.priceRatio = ''
        }
        if (isPriceValid && isOtherSupplierPriceValid) {
          row.otherSupplierPriceRatio = toPercent(otherSupplierPrice / price - 1, 3)
        } else {
          row.otherSupplierPriceRatio = ''
        }
      } else {
        // 临采价格核查
        switch (field) {
          case 'purchaseCount': // 订货数量
          case 'purchasePrice': // 订货价格
            if (isPurchaseCountValid && isPurchasePriceValid) {
              row.totalAmount = toFixed(purchaseCount * purchasePrice)
              if (isCheckPriceValid) {
                row.balance = toFixed((checkPrice - purchasePrice) * purchaseCount)
              }
              if (isOtherSupplierPriceValid) {
                row.otherSupplierBalance = toFixed((otherSupplierPrice - purchasePrice) * purchaseCount)
              }
            } else {
              row.totalAmount = ''
            }
            break;
          case 'checkPrice':
            // 核查价格
            if (isPurchaseCountValid && isPurchasePriceValid && isCheckPriceValid) {
              row.balance = toFixed((checkPrice - purchasePrice) * purchaseCount)
            } else {
              row.balance = ''
            }
            break;
          case 'otherSupplierPrice':
            // 其他供应商价格
            if (isPurchaseCountValid && isPurchasePriceValid && isOtherSupplierPriceValid) {
              row.otherSupplierBalance = toFixed((otherSupplierPrice - purchasePrice) * purchaseCount)
            } else {
              row.otherSupplierBalance = ''
            }
            break;
        }
        const { balance, otherSupplierBalance, totalAmount } = row
        const isTotalAmountValid = totalAmount && !isNaN(totalAmount)
        const isBalanceValid = balance !== '' && !isNaN(balance)
        const isOtherBalanceValid = otherSupplierBalance !== '' && !isNaN(otherSupplierBalance)
        if (isTotalAmountValid && (isBalanceValid || isOtherBalanceValid)) {
          let priceRatio = 0
          if (isBalanceValid && isOtherBalanceValid) {
            priceRatio = Math.min(balance, otherSupplierBalance) / totalAmount
          } else if (isBalanceValid) {
            priceRatio = balance / totalAmount
          } else {
            priceRatio = otherSupplierBalance / totalAmount
          }
          if (priceRatio !== '' && !isNaN(priceRatio)) {
            row.priceRatio = toPercent(priceRatio, 3)
          } else {
            row.priceRatio = ''
          }
        } else {
          row.priceRatio = ''
        }
      }
    },
    // 表格删除行
    async removeEvent (row, index) {
      this.$refs.table.remove(row)
      this.tableList.splice(index, 1)
    },
    // 获取数据
    // isValidity 先验证表单，通过后返回数据
    getData (isValidity = false) {
      const { tableList, $message, isTemp } = this
      return new Promise(async (resolve, reject) => {
        const validateForm = () => {
        // validate form
          this.$refs['form'].validate((valid) => {
            this.valid = valid
            if (valid) {
              if (tableList && tableList.length) {
                validateTable()
              } else {
                $message.error(isTemp ? '请关联商品或关联单据！' : '请关联商品！')
              }
            } else {
              return false;
            }
          })
        }

        const validateTable = async () => {
          const errMap = await this.$refs.table.fullValidate(true)
          if (errMap) {
            console.log('errMap', errMap)
          } else {
            // 返回数据
            resolve(this.formData)
          }
        }

        // 验证各个表单
        if (isValidity) {
          validateForm()
          // validateTable()
        } else {
          // 返回数据
          resolve(this.formData)
        }
      })
    },
    handleInputChange () {
      this.$refs.table.clearValidate()
    },
  },
}
</script>

<style lang="less">
.supervision-form-content {
  & + .actions {
    margin-top: 20px;
    text-align: center;
  }
  .supervision-detail {
    margin: 16px 0;
    border-top: 1px solid #eee;
    border-bottom: 1px solid #eee;
    .el-col-6 {
      display: flex;
      align-items: center;
      min-height: 50px;
    }
    .label {
      flex: 0 0 100px;
      text-align: right;
    }
    .ellipsis {
      white-space: nowrap;
      overflow: hidden; /*超出的文本隐藏*/
      text-overflow: ellipsis; /* 溢出用省略号*/
    }
  }
  .buttons-bar {
    margin-bottom: 12px;
  }
  pre{
    padding: 10px;
    border: 1px solid #eee;
  }
  .el-form-item__content .el-input-group {
    vertical-align: baseline;
  }
}
</style>
